package cn.edu.swu.pager;

import cn.edu.swu.book.BOOK;
import cn.edu.swu.book.bookRepo;
import cn.edu.swu.common.Conf;
import cn.edu.swu.pager.Pager;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/queryPage")
public class pageServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String page = req.getParameter("page");
            System.out.println(page);
            int curPage = page != null ? Integer.valueOf(page) : 1;
            String page_size = req.getParameter("pageSize");
            int pageSize = page_size != null ? Integer.valueOf(page_size) : Conf.PAGE_SIZE;
            int offset=(curPage-1)*pageSize;

            Pager pager=new Pager();
            pager.setPageSize(pageSize);
            pager.setTotalPages(bookRepo.getInstance().totalBookPages(pager.getPageSize()));
            pager.setCurPage(curPage);
            String sql=String.format("select * from book limit %s offset %s",pageSize,offset);
            List<BOOK> books= bookRepo.getInstance().queryBook(sql);
            pager.setBooks(books);

            ObjectMapper objectMapper=new ObjectMapper();
            String json=objectMapper.writeValueAsString(pager);


            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            try(Writer writer=resp.getWriter()){
                writer.write(json);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
